package com.gitee.huxing.course.conc.conc02.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.conc02.lock
 * @ClassName: ConditionDemo
 * @Author: huxing
 * @DateTime: 2021-08-24 下午7:05
 */
public class ConditionDemo {

    final Lock lock = new ReentrantLock();
    final Condition notFull = lock.newCondition();
    final Condition notEmpty = lock.newCondition();

    final Object[] items = new Object[20];
    int putptr, takeptr, count;

    /**
     * 存入
     * @param x
     * @throws Exception
     */
    public void put(Object x) throws Exception{
        lock.lock();
        try {
            // 当count等于数组大小时，当前线程等待，直到notFull通知，在进行生产
            while (count == items.length){
                notFull.await();
            }
            items[putptr] = x;
            if (++putptr == items.length){
                putptr = 0;
            }
            ++count;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 取出
     * @return
     * @throws Exception
     */
    public Object take() throws Exception{
        lock.lock();
        try {
            // 当count为0，进入等待，直到notEmpty通知，进行消费
            while (count == 0){
                notEmpty.wait();
            }
            Object x = items[takeptr];
            if (++takeptr == items.length){
                takeptr = 0;
            }
            --count;
            notFull.signal();
            return x;
        }finally {
            lock.unlock();
        }
    }
}
